// yjs-ws-server.js
const WebSocket = require('ws')
const http = require('http')
const setupWSConnection = require('y-websocket/bin/utils').setupWSConnection

const port = process.env.PORT || 1234
const host = process.env.HOST || '192.168.5.63' // 指定监听地址（可改成你的 IP）

const server = http.createServer((req, res) => {
  res.writeHead(200)
  res.end('Yjs WebSocket Server')
})

const wss = new WebSocket.Server({ server })

wss.on('connection', (ws, req) => {
  // 注意：path 可根据你客户端连接URL修改，比如 '/my-room'
  const params = new URL(req.url, `http://${req.headers.host}`)
  const docName = params.pathname.slice(1) || 'default-room'

  setupWSConnection(ws, req, { docName })
})

server.listen(port, host, () => {
  console.log(`✅ Yjs WebSocket server running on ws://${host}:${port}`)
})
